package org.lex.dbq.view.sql;

import java.sql.Connection;
import java.util.concurrent.ExecutionException;

import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.lex.dbq.DBQApplication;
import org.lex.dbq.model.jdbc.object.ObjectNode;
import org.lex.dbq.model.jdbc.object.ObjectTreeBuilder;
import org.lex.swt.SWTWorker;
import org.lex.swt.app.ActionMap;
import org.lex.swt.tree.TreeNodeContentProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ObjectPane extends Composite {
	TreeViewer tree = null;
	private Connection conn = null;

	private Logger log = LoggerFactory.getLogger(ObjectPane.class);

	public ObjectPane(Composite parent, int style) {
		super(parent, style);
		this.initialize();
	}

	public void setConnection(final Connection conn) {
		this.conn = conn;
		try {
			new SWTWorker<ObjectNode>() {
				@Override
				protected ObjectNode doInBackground() throws Exception {
					ObjectTreeBuilder builder = new ObjectTreeBuilder(conn);
					return builder.build();
				}

				@Override
				protected void done() {
					try {
						ObjectNode root = this.get();
						log.info("root=" + root);
						tree.setInput(root);
						tree.refresh();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ExecutionException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}.execute();
		} catch (Exception e) {
			log.error("", e);
		}
	}

	ITreeSelection getSelection() {
		return (ITreeSelection) tree.getSelection();
	}

	private void initialize() {
		this.setLayout(new FillLayout());
		tree = new TreeViewer(this);
		tree.setContentProvider(new TreeNodeContentProvider());
		tree.setLabelProvider(new LabelProvider());
		tree.setInput(root());
		// create popup
		ActionMap am = DBQApplication.getApplication().getContext().getActionService().getActionMap(
				SqlActions.ACTION_MAP_NAME);

		MenuManager popup = new MenuManager();
		popup.add(am.get(SqlActions.editTable));
		popup.add(am.get(SqlActions.queryData));

		Menu m = popup.createContextMenu(tree.getTree());
		tree.getTree().setMenu(m);
		m.addMenuListener(new MenuAdapter() {
			@Override
			public void menuShown(MenuEvent e) {
				ITreeSelection s = (ITreeSelection) tree.getSelection();
				System.out.println("Selection: " + s);
			}
		});
	}

	public ObjectNode root() {
		ObjectNode root = new ObjectNode();
		root.setData("root");
		return root;
	}
}
